/**
 * <p>Project: questionnaire</p>
 * <p>Copyright: Copyright (c) 2015 7dub.cn</p>
 * <p>Company: 柒色都吧7dub.cn</p>
 */

package com.daervin.controller.manager;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.validation.Valid;

import com.daervin.common.entity.MsgEntity;
import com.daervin.common.utils.CurrentUserUtils;
import com.daervin.common.utils.EncryptUtils;
import com.daervin.form.manager.survey.AddAnswerForm;
import com.daervin.form.manager.survey.AddSurveyForm;
import com.daervin.service.manager.survey.ISurveyService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daervin.common.entity.ValidError;
import com.daervin.common.shiro.ShiroUser;
import com.daervin.entity.manager.survey.Question;
import com.daervin.entity.manager.survey.Survey;
import com.daervin.form.manager.survey.AddQuestionAndOptionsForm;
import com.daervin.form.manager.survey.FindSurveyListForm;
import com.daervin.service.manager.survey.IAnswerService;
import com.daervin.service.manager.survey.IQuestionService;

import com.github.pagehelper.PageInfo;

/**
 * 问卷发布中心控制器。
 * 
 * @author daervin (2015年5月10日 下午1:37:12)
 *
 * @since 1.0.0
 *
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/manager")
public class SurveyController {

    @Inject
    private ISurveyService surveyService;

    @Inject
    private IQuestionService questionService;

    @Inject
    private IAnswerService answerService;

    /**
     * 问卷中心首页。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/list")
    public String list(@ModelAttribute("form") @Valid FindSurveyListForm form, BindingResult bindingResult, ModelMap model) {
        ShiroUser user = CurrentUserUtils.getCurrentUser(); // 获取当前登录用户信息
        model.addAttribute("user", user);

        PageInfo<Survey> pageInfo = null;
        List<Survey> topList = null;
        List<ValidError> errorList = new ArrayList<ValidError>();
        // JSR303数据校验
        if (bindingResult.hasErrors()) {
            for (FieldError fe : bindingResult.getFieldErrors()) {
                ValidError error = new ValidError(fe.getField(), fe.getDefaultMessage());
                errorList.add(error);
            }

            model.addAttribute("errorList", errorList);
        }
        else {
            pageInfo = this.surveyService.findsAllByParameter(form);
            topList = this.surveyService.findsTop();
        }

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("topList", topList);

        return "manager/survey/list";
    }

    /**
     * 创建空白问卷展示页面。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/createView")
    public String createView(ModelMap model) {
        ShiroUser user = CurrentUserUtils.getCurrentUser(); // 获取当前登录用户信息
        model.addAttribute("user", user);
        return "manager/survey/createView";
    }

    /**
     * 新增問卷。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "/addSurvey", method = RequestMethod.POST)
    public MsgEntity addSurvey(AddSurveyForm form) {
        // TODO 数据校验
        MsgEntity msg = new MsgEntity(false, "新增问卷出错！");
        String id = this.surveyService.addSurvey(form);

        if (id != null) {
            msg.setStatus(true);
            msg.setOthers(id);
            msg.setMsg("新增问卷成功，下一步新增问题...");
        }
        return msg;
    }

    /**
     * 创建问题展示页面。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/questionView/{surveyId}")
    public String createQuestionView(@PathVariable("surveyId") String surveyId, ModelMap model) {
        ShiroUser user = CurrentUserUtils.getCurrentUser(); // 获取当前登录用户信息
        model.addAttribute("user", user);

        Survey survey = this.surveyService.findById(surveyId); // 当前问卷信息
        model.addAttribute("survey", survey);
        return "manager/survey/createQuestionView";
    }

    /**
     * 新增题目和选项。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "/addQO", method = RequestMethod.POST)
    public MsgEntity addQuestionAndOptions(@Valid AddQuestionAndOptionsForm form, BindingResult bindingResult) {
        MsgEntity msg = new MsgEntity(false, "新增题目出错！");

        // JSR303数据校验
        if (bindingResult.hasErrors()) {
            List<ValidError> errorList = new ArrayList<ValidError>();
            for (FieldError fe : bindingResult.getFieldErrors()) {
                ValidError error = new ValidError(fe.getField(), fe.getDefaultMessage());
                errorList.add(error);
            }

            msg.setOthers(errorList);
            return msg;
        }

        if (this.questionService.add(form)) {
            msg.setStatus(true);
            msg.setMsg("新增题目成功！");
        }

        return msg;
    }

    /**
     * 创建问题展示页面。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/qaView/{surveyId}")
    public String questionAnswerView(@PathVariable("surveyId") String surveyId, ModelMap model) {
        List<Question> pageInfo = this.questionService.findsQuestion(surveyId); // 当前问卷题目信息
        model.addAttribute("pageInfo", pageInfo);
        return "manager/survey/qaView";
    }

    /**
     * 问卷详情展示页面。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/details/{surveyId}")
    public String surveyDetails(@PathVariable("surveyId") String surveyId, ModelMap model) {
        ShiroUser user = CurrentUserUtils.getCurrentUser(); // 获取当前登录用户信息
        model.addAttribute("user", user);

        Survey survey = this.surveyService.detailsById(surveyId); // 当前问卷信息
        model.addAttribute("survey", survey);

        List<Question> questionInfo = this.questionService.findsQuestion(surveyId); // 当前问卷题目信息
        model.addAttribute("questionInfo", questionInfo);
        return "manager/survey/details";
    }

    /**
     * 非公开问卷检查密钥。
     *
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping("/checkPwd")
    public boolean checkPwd(@ModelAttribute("pwd") String pwd, @ModelAttribute("surveyId") String surveyId) {
        boolean success = false;
        Survey survey = this.surveyService.findById(surveyId); // 当前问卷信息
        if (survey != null && survey.getPassword().equals(EncryptUtils.encryptMD5(pwd))) {
            success = true;
        }
        return success;
    }

    /**
     * 新增答卷。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "/addAnswer", method = RequestMethod.POST)
    public MsgEntity addAnswer(@Valid AddAnswerForm form, BindingResult bindingResult, ModelMap model) {
        MsgEntity msg = new MsgEntity(false, "答卷提交出错或您已填写过此问卷！");

        // JSR303数据校验
        if (bindingResult.hasErrors()) {
            return msg;
        }

        if (this.answerService.insert(form)) {
            msg.setStatus(true);
            msg.setMsg("答卷提交中...");
        }

        return msg;
    }

    /**
     * 填写问卷结果提示页面。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/resualtInfo")
    public String resualtInfo(ModelMap model) {
        ShiroUser user = CurrentUserUtils.getCurrentUser(); // 获取当前登录用户信息
        model.addAttribute("user", user);

        return "manager/survey/resualtInfo";
    }

    /**
     * 统计单个问卷。
     *
     * @since 1.0.0
     * @version 1.0.0
     */
    @RequestMapping("/summary/{sid}")
    public String summary(@PathVariable("sid") String sid, ModelMap model) {
        Survey survey = this.surveyService.findById(sid); // 当前问卷信息
        List<Question> list = this.questionService.findsQuestion(sid); // 当前问卷的题目信息

        model.addAttribute("survey", survey);
        model.addAttribute("quelist", list);

        return "manager/survey/summary";
    }

}
